<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">{{ pageTitle }}</div>
      <q-space></q-space>
      <search-bar-toggle-btn v-model="searchBarVisibility"></search-bar-toggle-btn>
    </div>
    <!--查询-->
    <div class="q-pa-sm shadow-2 q-mb-md items-center" v-show="searchBarVisibility">
      <div class="row q-col-gutter-sm">
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">任务ID</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.taskId" :readonly="listDataLoadingState" @keyup.enter="loadListData(2)" ></easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">仓库</div>
          <div class="col-8">
            <simple-filter-select :options="$d.whDropdownList" :readonly="listDataLoadingState" :use-filter="false"
                option-label="whName" option-value="whId" v-model="fpsReq.whId" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">WCS任务类型</div>
          <div class="col-8">
            <simple-filter-select :auto-select-single-option="false" :options="$d.taskTypeDropdownList"
                v-model="fpsReq.robotTaskType" :use-filter="false" :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">WMS任务类型</div>
          <div class="col-8">
            <simple-filter-select :auto-select-single-option="false" :options="$d.taskTypeDropdownList"
                v-model="fpsReq.wmsTaskType" :use-filter="false" :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">区域站点</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.slotCode" :readonly="listDataLoadingState" @keyup.enter="loadListData(2)" ></easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">来源储位</div>
          <div class="col-8">
            <simple-filter-select
                :options="$d.locDropdownList"
                :readonly="listDataLoadingState"
                option-label="loc"
                option-value="locId"
                v-model="fpsReq.fromLocId"
                server-side-url="/wms/basic/loc/get-loc-simple-list"
                search-content-field="loc"
                resp-data-field="locs"
                :req-params="{pageNo:1,pageSize:10,whId:fpsReq.whId}" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">目的储位</div>
          <div class="col-8">
            <simple-filter-select
                :options="$d.locDropdownList"
                :readonly="listDataLoadingState"
                option-label="loc"
                option-value="locId"
                v-model="fpsReq.toLocId"
                server-side-url="/wms/basic/loc/get-loc-simple-list"
                search-content-field="loc"
                resp-data-field="locs"
                :req-params="{pageNo:1,pageSize:10,whId:fpsReq.whId}" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">容器号</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.container" :readonly="listDataLoadingState" @keyup.enter="loadListData(2)" ></easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">状态</div>
          <div class="col-8">
            <simple-filter-select :auto-select-single-option="false" :options="$d.stateDropdownList"
                v-model="fpsReq.state" :use-filter="false" :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">创建日期从</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.createDtBegin" use-date-picker append-icon-show :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">创建日期至</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.createDtEnd" use-date-picker append-icon-show :readonly="listDataLoadingState" />
          </div>
        </div>

        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">任务组号</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.groupId" :readonly="listDataLoadingState" @keyup.enter="loadListData(2)" ></easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">WCS机器执行节点</div>
          <div class="col-8">
            <simple-filter-select :auto-select-single-option="false" :options="$d.robotStateDropdownList"
                v-model="fpsReq.robotState" :use-filter="false" :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3">
          <div class="row col-12 q-col-gutter-sm">
            <q-toggle v-model="fpsReq.isWmsExeSuccess" @update:model-value="loadListData(2)" :disable="listDataLoadingState"  label="WMS内部业务是否执行失败" toggle-indeterminate
                 dense class="q-ma-xs" style="margin: 0 auto; line-height: 36px; height: 36px" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3">
          <div class="row col-12 q-col-gutter-sm">
            <q-toggle v-model="fpsReq.noInitState" @update:model-value="loadListData(2)" :disable="listDataLoadingState"  label="WCS机器执行节点" toggle-indeterminate
                 dense class="q-ma-xs" style="margin: 0 auto; line-height: 36px; height: 36px" />
          </div>
        </div>
      </div>
      <div class="row q-pt-sm">
        <div class="q-mr-sm">
          <q-btn :disable="listDataLoadingState" @click="loadListData(2)" color="primary" icon="search" label="查询" />
        </div>
      </div>
    </div>
    <div class="shadow-2">
      <q-table :columns="fpsInfo.columnsInfo" :rows="$d.tableData" :hide-pagination="true"
          :loading="listDataLoadingState" row-key="taskId"
          :visible-columns="fpsInfo.visibleColumns" @request="fpsAssist.onDataTableRequest"
          v-model:pagination="fpsInfo.paginationInfo" selection="multiple" v-model:selected="$d.selectedItems"
          binary-state-sort color="primary" dense flat separator="cell">
        <template v-slot:top="props">
          <!--功能按钮-->
          <div class="q-gutter-sm">
            <q-btn :disable="listDataLoadingState || $d.selectedItems.length !== 1" @click="cancelRbTask" color="primary" label="取消任务"
                v-if="fx.hasModifyRight('Wms.Wcs.RobotTask.Cancel')" />
            <q-btn :disable="listDataLoadingState || $d.selectedItems.length === 0" @click="reExecuteWmsFunction" color="primary" label="重新执行WMS内部业务"
                v-if="fx.hasModifyRight('Wms.Wcs.RobotTask.ReExecuteWmsFunction')" />
            <q-btn :disable="listDataLoadingState || $d.selectedItems.length === 0" @click="reAddRobotaTasks" color="primary" label="重新加到任务中"
                v-if="fx.hasModifyRight('Wms.Wcs.RobotTask.ReAddRobotaTasks')" />
          </div>
          <q-space />
          <table-col-options-cfg v-model:visible-columns="fpsInfo.visibleColumns"
              v-model:table-columns="fpsInfo.columnsInfo" class="q-mx-sm"
              @update-col-options-for-save="fpsAssist.saveColOptions"></table-col-options-cfg>
          <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" :ripple="false"
              :title="props.inFullscreen ? '退出全屏' : '全屏显示'" dense flat @click="props.toggleFullscreen" />
        </template>
        <template v-slot:no-data>
          <span class="full-width text-center">
            <q-icon name="error_outline" />
            无数据
            <q-btn flat icon="refresh" :loading="listDataLoadingState"
                :disable="listDataLoadingState" dense title="刷新" size="sm" class="q-ml-sm" @click="loadListData"></q-btn>
            </span>
        </template>
        <!--状态列插槽-->
        <template v-slot:body-cell-state="props">
          <q-td :props="props" auto-width>
            <q-badge :color="fmtState(props.row.state)[1]" :label="fmtState(props.row.state)[0]" />
          </q-td>
        </template>
        <template v-slot:bottom>
          <paging-bar :loading-state="listDataLoadingState" :pageNo="fpsReq.pageNo" :pageSize="fpsReq.pageSize"
              :totalAmount="fpsInfo.totalAmount" @pagesize-changed="fpsAssist.onPageSizeChanged"
              @go-to-page="fpsNav.gotoPage" />
        </template>
        <template v-slot:body-cell-isMoved="props">
          <q-td :props="props" auto-width>
            <q-badge :color="props.row.isMoved ? 'positive' : 'red' " :label="props.row.isMoved ? '已完成' : '未完成'" />
          </q-td>
        </template>
        <!--wms内部业务是否执行成功-->
        <template v-slot:body-cell-isWmsExeSuccess="props">
          <q-td :props="props" auto-width>
            <q-badge color="positive" label="成功" v-if="props.row.isWmsExeSuccess" />
            <q-badge color="red" label="失败" v-if="props.row.isWmsExeSuccess === false" />
          </q-td>
        </template>
      </q-table>
    </div>
  </q-page>
</template>
<script setup lang="ts">
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {useFpsHelper} from '@njt/foundation/hooks/fpsHelper'
import {reactive, ref} from 'vue'
import {GetRbTaskListReq, GetRbTaskListResp, MhlBcRobotTask} from 'src/defs/robotTask'
import {ColumnInfo} from '@njt/foundation/defs/comm'
import {WmWhLite} from '@njt/wms/defs/basic/wh'
import _ from 'lodash'
import {WmLoc} from '@njt/wms/defs/basic/loc'
import { useRoute } from 'vue-router';

const pageTitle = 'WCS任务'
useTitleHelper(pageTitle)
let listDataLoadingState = ref(false)

let fpsReq: GetRbTaskListReq = reactive({
  taskId: null,
  whId: null,
  robotTaskType: null,
  wmsTaskType: null,
  slotCode: null,
  fromLocId: null,
  toLocId: null,
  container: null,
  groupId: null,
  state: null,
  robotState: null,
  noInitState: null,
  isWmsExeSuccess: null,
  createDtBegin: null,
  createDtEnd: null,
  pageNo: 1,
  pageSize: 40,
  isDescending: false,
  orderBy: null,
  sku: null
})

// 列参数
const columnsDefine: ColumnInfo[] = [
      {
        label: '任务ID',
        name: 'taskId',
        field: 'taskId',
        align: 'left',
        defOrder: 2,
        sortable: true,
        defVisible: true
      },
      {
        label: '仓库ID',
        name: 'whId',
        field: 'whId',
        align: 'left',
        defOrder: 3,
        defVisible: false
      },
      {
        label: '仓库',
        name: 'whName',
        field: 'whName',
        align: 'left',
        defOrder: 4,
        sortable: true,
        defVisible: true
      },
      {
        label: '外部任务类型',
        name: 'robotTaskType',
        field: 'robotTaskType',
        align: 'left',
        defOrder: 5,
        sortable: true,
        defVisible: true,
        format: (value) => fmtTaskType(value)
      },
      {
        label: 'WMS任务类型',
        name: 'wmsTaskType',
        field: 'wmsTaskType',
        align: 'left',
        defOrder: 6,
        sortable: true,
        defVisible: true,
        format: (value) => fmtTaskType(value)
      },
      {
        label: '源ID',
        name: 'sourceId',
        field: 'sourceId',
        align: 'left',
        defOrder: 7,
        defVisible: true
      },
      {
        label: '来源储位ID',
        name: 'fromLocId',
        field: 'fromLocId',
        align: 'left',
        defOrder: 8,
        defVisible: false
      },
      {
        label: '来源储位',
        name: 'fromLoc',
        field: 'fromLoc',
        align: 'left',
        defOrder: 9,
        defVisible: true
      },
      {
        label: '目的储位ID',
        name: 'toLocId',
        field: 'toLocId',
        align: 'left',
        defOrder: 10,
        defVisible: false
      },
      {
        label: '目的储位',
        name: 'toLoc',
        field: 'toLoc',
        align: 'left',
        defOrder: 11,
        defVisible: true
      },
      {
        label: '容器号',
        name: 'container',
        field: 'container',
        align: 'left',
        defOrder: 12,
        sortable: true,
        defVisible: true
      },
      {
        label: '区域站点',
        name: 'slotCode',
        field: 'slotCode',
        align: 'left',
        defOrder: 12,
        sortable: true,
        defVisible: true
      },
      {
        label: '任务组号',
        name: 'groupId',
        field: 'groupId',
        align: 'left',
        defOrder: 13,
        sortable: true,
        defVisible: true
      },
      {
        label: '优先级',
        name: 'priority',
        field: 'priority',
        align: 'left',
        defOrder: 14,
        sortable: true,
        defVisible: true
      },
      {
        label: '状态',
        name: 'state',
        field: 'state',
        align: 'left',
        defOrder: 15,
        sortable: true,
        defVisible: true
      },
      {
        label: '备注',
        name: 'remark',
        field: 'remark',
        align: 'left',
        defOrder: 16,
        defVisible: true
      },
      {
        label: 'wms内部业务是否执行成功',
        name: 'isWmsExeSuccess',
        field: 'isWmsExeSuccess',
        align: 'left',
        defOrder: 17,
        sortable: true,
        defVisible: true
      },
      {
        label: 'wms内部业务执行返回信息',
        name: 'wmsExeRtnMsg',
        field: 'wmsExeRtnMsg',
        align: 'left',
        defOrder: 18,
        defVisible: true
      },
      {
        label: '任务执行来源',
        name: 'isTaskExecutedFromWcs',
        field: 'isTaskExecutedFromWcs',
        align: 'left',
        defOrder: 19,
        defVisible: true,
        format: (value: boolean) => value ? 'wcs方主动执行' : 'wms方主动执行'
      },
      {
        label: '创建时间',
        name: 'createDt',
        field: 'createDt',
        align: 'left',
        defOrder: 20,
        defVisible: true,
        format: (value) => $f.fmt.dtFmtFullNoSec(value)
      },
      {
        label: '执行指令发送时间',
        name: 'exeCmdSendDt',
        field: 'exeCmdSendDt',
        align: 'left',
        defOrder: 21,
        defVisible: true,
        format: (value) => $f.fmt.dtFmtFullNoSec(value)
      },
      {
        label: '执行指令发送结果',
        name: 'exeCmdSendResMsg',
        field: 'exeCmdSendResMsg',
        align: 'left',
        defOrder: 22,
        defVisible: true
      },
      {
        label: '执行指令返回时间',
        name: 'exeCmdRtnDt',
        field: 'exeCmdRtnDt',
        align: 'left',
        defOrder: 23,
        defVisible: true,
        format: (value) => $f.fmt.dtFmtFullNoSec(value)
      },
      {
        label: '执行指令返回消息',
        name: 'exeCmdRtnMsg',
        field: 'exeCmdRtnMsg',
        align: 'left',
        defOrder: 24,
        defVisible: true
      },
      {
        label: '取消指令发送时间',
        name: 'cancelCmdSendDt',
        field: 'cancelCmdSendDt',
        align: 'left',
        defOrder: 25,
        defVisible: true,
        format: (value) => $f.fmt.dtFmtFullNoSec(value)
      },
      {
        label: '取消指令发送结果',
        name: 'cancelCmdSendResMsg',
        field: 'cancelCmdSendResMsg',
        align: 'left',
        defOrder: 26,
        defVisible: true
      },
      {
        label: '取消指令返回时间',
        name: 'cancelCmdRtnDt',
        field: 'cancelCmdRtnDt',
        align: 'left',
        defOrder: 27,
        defVisible: true,
        format: (value) => $f.fmt.dtFmtFullNoSec(value)
      },
      {
        label: '取消指令返回消息',
        name: 'cancelCmdRtnMsg',
        field: 'cancelCmdRtnMsg',
        align: 'left',
        defOrder: 28,
        defVisible: true
      },
      {
        label: 'wcs机器执行节点',
        name: 'robotState',
        field: 'robotState',
        align: 'left',
        defOrder: 30,
        defVisible: true,
        format: (value) => fmtRobotState(value)
      }
    ]

const $d = reactive({
  locDropdownList: [] as WmLoc[],
  tableData: [] as MhlBcRobotTask[],
  // 多选数据源
  selectedItems: [] as MhlBcRobotTask[],
  // 仓库下拉
  whDropdownList: [] as WmWhLite[],
  // 任务类型下拉
  taskTypeDropdownList: [
    {
      label: '上架',
      value: 'putaway'
    },
    {
      label: '拣货',
      value: 'pick'
    },
    {
      label: '有单移库',
      value: 'docMove'
    },
    {
      label: '空托盘转移',
      value: 'emptyLpn'
    }
  ] as Record<string, string>[],
  // 状态下拉
  stateDropdownList: [
    {
      label: '初始',
      value: '0'
    },
    {
      label: '执行中',
      value: '3'
    },
    {
      label: '执行成功',
      value: '9'
    },
    {
      label: '取消',
      value: 'C'
    },
    {
      label: '执行失败',
      value: 'X'
    }
  ],
  robotStateDropdownList: [
    {
      label: '未收到命令',
      value: '0'
    },
    {
      label: '命令已下发到设备',
      value: '90502'
    },
    {
      label: '取货完成',
      value: '90504'
    },
    {
      label: '卸货完成',
      value: '90506'
    },
    {
      label: '任务完成',
      value: '90507'
    },
    {
      label: '任务取消',
      value: '90508'
    }
  ],
})

const loadListData = (resetFpsReq?: number) => {
  if (resetFpsReq) {
    if (resetFpsReq >= 1) {
      fpsReq.pageNo = 1
    }
    if (resetFpsReq >= 2) {
      fpsReq.orderBy = ''
      fpsReq.isDescending = false
    }
  }
  listDataLoadingState.value = true
  $f.axios.get<GetRbTaskListResp>('/mhlbc/wcs/get-rb-task-list', {params: fpsReq})
      .then((result) => {
        if (result.data.createDtBegin) {
          result.data.createDtBegin = $f.fmt.dtFmtDateOnly(result.data.createDtBegin)
        }
        if (result.data.createDtEnd) {
          result.data.createDtEnd = $f.fmt.dtFmtDateOnly(result.data.createDtEnd)
        }
        fpsAssist.handleGenericFpsResp(result.data)
        $d.tableData = result.data.rbTaskList
        fpsAssist.saveFpsReq(fpsReq)
      })
      .catch((err) => {
        $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
      })
      .finally(() => {
        listDataLoadingState.value = false
      })
}


const {
  fpsInfo,
  fpsAssist,
  fpsNav,
  searchBarVisibility
} = useFpsHelper('/wms/task/rb',
    null,
    null,
    null,
    fpsReq, columnsDefine,
    null,
    loadListData)

// 任务类型格式化
const fmtTaskType = (value: string) => {
  switch (value) {
    case 'putaway':
      return '上架'
    case 'pick':
      return '拣货'
    case 'docMove':
      return '有单移库'
    case 'abnormal':
      return '异常'
    default:
      return null
  }
}
// 状态格式化
const fmtState = (state: string) => {
  switch (state) {
    case '0':
      return ['初始', 'info']
    case '3':
      return ['执行中', 'blue-6']
    case '9':
      return ['执行成功', 'positive']
    case 'C':
      return ['取消', 'grey-6']
    case 'X':
      return ['执行失败', 'red']
    default:
      return [null, null]
  }
}
// 执行节点格式化
const fmtRobotState = (robotState: string) => {
  switch (robotState) {
    case '0':
      return '未收到命令'
    case '90502':
      return '命令已下发到设备'
    case '90504':
      return '取货完成'
    case '90506':
      return '卸货完成'
    case '90507':
      return '任务完成'
    case '90508':
      return '任务取消'
    default:
      return null
  }
}

// 取消任务
const cancelRbTask = () => {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要取消选中任务吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios.post('/mhlbc/wcs/cancel-rb-task/' + $d.selectedItems[0].taskId)
        .then(() => {
          $f.ui.closeMsgBox()
          loadListData()
          $d.selectedItems = []
        })
        .catch((err) =>{
          void $f.ui.messageBox({
            caption: '取消任务失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}
// 重新执行WMS内部业务
const reExecuteWmsFunction = () => {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要重新执行WMS内部业务吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios.post('/mhlbc/wcs/re-execute-wms-function', _.map($d.selectedItems, 'taskId'))
          .then(() => {
            $f.ui.closeMsgBox()
            loadListData()
            $d.selectedItems = []
          })
          .catch((err) =>{
            void $f.ui.messageBox({
              caption: '重新执行失败',
              text: $f.getAxiosErrMsg(err),
              icon: $f.getAxiosErrIcon(err),
              buttons: 'Close'
            })
          })
    }
  })
}

// 将失败的任务重新加入WCS任务列表中
const reAddRobotaTasks = () => {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要重新加到任务中吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios.post('/mhlbc/wcs/re-add-robot-tasks', _.map($d.selectedItems, 'taskId'))
          .then(() => {
            $f.ui.closeMsgBox()
            loadListData()
            $d.selectedItems = []
          })
          .catch((err) =>{
            void $f.ui.messageBox({
              caption: '重新加到任务中失败',
              text: $f.getAxiosErrMsg(err),
              icon: $f.getAxiosErrIcon(err),
              buttons: 'Close'
            })
          })
    }
  })
}
// 仓库下拉
void $f.lst.getWmWhSimpleList()
    .then((resp) => {
      $d.whDropdownList = resp
    })

const route = useRoute()
let params = route.query
if (params) {
  $f.misc.simpleAssign(fpsReq, params)
}
const fx = $f
</script>
